﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Mailer.Utilities
{
	public class MailID
	{
		public string Raw { get; set; }
		public string Extras { get; set; }
		public Guid Mail { get; set; }
		public Guid Recipient { get; set; }

		public MailID()
		{
			Raw = "";
			Extras = "";
			Mail = Guid.Empty;
			Recipient = Guid.Empty;
		}

		public static MailID Parse(string rawcode)
		{
			MailID ret = new MailID();

			ret.Raw = rawcode;

			Match m1;

			m1 = Regex.Match(rawcode, "[\\.^]?M([a-f0-9-]+)[\\.$]?", RegexOptions.Singleline | RegexOptions.IgnoreCase);
			if (m1.Success)
				if (m1.Groups.Count == 2)
					ret.Mail = new Guid(m1.Groups[1].Value);

			m1 = Regex.Match(rawcode, "[\\.^]?R([a-f0-9-]+)[\\.$]?", RegexOptions.Singleline | RegexOptions.IgnoreCase);
			if (m1.Success)
				if (m1.Groups.Count == 2)
					ret.Recipient = new Guid(m1.Groups[1].Value);

			m1 = Regex.Match(rawcode, "[\\.^]?X([a-z0-9]+)[\\.$]?", RegexOptions.Singleline | RegexOptions.IgnoreCase);
			if (m1.Success)
				if (m1.Groups.Count == 2)
					ret.Extras = m1.Groups[1].Value;

			return ret;
		}

		public static string Generate(Guid mail)
		{
			return Generate(mail, Guid.Empty, "");
		}

		public static string Generate(Guid mail, Guid recipient)
		{
			return Generate(mail, recipient, "");
		}

		public static string Generate(Guid mail, Guid recipient, string extras)
		{
			string trackid = "";
			if (mail != Guid.Empty)
			{
				if (trackid != "")
					trackid += ".";
				trackid += "M" + mail;
			}

			if (recipient != Guid.Empty)
			{
				if (trackid != "")
					trackid += ".";
				trackid += "R" + recipient;
			}

			if (!string.IsNullOrEmpty(extras))
			{
				if (trackid != "")
					trackid += ".";
				trackid += "X" + extras;
			}

			return trackid;
		}

	}
}
